package com.itheima.service.impl;

import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    //添加数据
    @Override
    public void add(List<OrderSetting> data) {
        //判断数据是否为空
        if (data!=null&&data.size()>0) {
            //遍历list添加数据
            for (OrderSetting orderSetting:data) {
                Date orderDate = orderSetting.getOrderDate();
                //判断当前的日期是否已经添加过
               long countByOrderDate= orderSettingDao.findCountByOrderDate(orderDate);
                if (countByOrderDate>0) {
                    //已经进行了设置,执行更新操作
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                }else{
                    //没有进行预约设置,执行插入操作
                    orderSettingDao.add(orderSetting);
                }

            }
        }

    }
    //查询对应时间的数据(返回map)
    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        //补全时间范围
        String begin=date+"-1";
        String end=date+"-31";
        Map<String,String> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        List<OrderSetting> list= orderSettingDao.getOrderSettingByMonth(map);
        List<Map> result=new ArrayList<>();

        result=list.stream().map(item ->{
            Map<String,Object> m=new HashMap<>();
            int orderDate = item.getOrderDate().getDate();
            int number = item.getNumber();
            int reservations = item.getReservations();
            m.put("date",orderDate);
            m.put("number",number);
            m.put("reservations",reservations);
            return m;

        }).collect(Collectors.toList());
        return result;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        Date orderDate = orderSetting.getOrderDate();
        //根据日期查询是否已经进行了预约设置
        long count = orderSettingDao.findCountByOrderDate(orderDate);
        if(count > 0){
            //当前日期已经进行了预约设置，需要执行更新操作
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else{
            //当前日期没有就那些预约设置，需要执行插入操作
            orderSettingDao.add(orderSetting);
        }
    }
}
